﻿package gateway;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.handler.codec.frame.FrameDecoder;

/**
 * 
 * 
 * 
 * @author kings
 * 
 */
public class MessageDecoder extends FrameDecoder {


	@Override
	protected Object decode(ChannelHandlerContext arg0, Channel channel,
			ChannelBuffer buffer) throws Exception {

		int readByteLength = buffer.readableBytes();

		if (readByteLength < 4) {
			return null;// (1)
		} else if (readByteLength == 23) {
			
			String xml = "<cross-domain-policy>";
			xml = xml + "<allow-access-from domain=\"*\" to-ports=\"*\" />";
	
			xml = xml + "</cross-domain-policy>";	
 
			ChannelBuffer bufferTmp = buffer.copy();
			byte[] b = new byte[23];
			bufferTmp.readBytes(b, 0, 23);
			String header = new String(b);
			if (header.equals("<policy-file-request/>\0")) {
				if (channel.isConnected()) {
					channel.write(xml + "\0");
				}
				return null;
			}
		}

		int dataLength = buffer.getInt(buffer.readerIndex());
		if (buffer.readableBytes() < dataLength + 4) {
			return null;// (2)
		}

		buffer.skipBytes(4);// (3)
//		byte[] decoded = new byte[dataLength];
//		buffer.readBytes(decoded);
//		String msg = new String(decoded);// (4)
		return buffer;

	}

}
